#pragma once
#include <QObject>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>

#include "fileutils.h"

/* 数据结构
 * jsobj{
 *  remark1: jsobj{
 *      name:''
 *      ip:''
 *      passwd:''
 *  }
 *  remark2:{...}
 *  ...
 * }
 */

class Mainwork: public QObject
{
    Q_OBJECT
public:
    Mainwork()
    {
        std::string jsonStr;
        ytool::create_directory("my_app/ssh");
        ytool::read_file(address, jsonStr);

        mjsonConfig = QJsonDocument::fromJson(QByteArray(jsonStr.data())).object();
    }

signals:
    void jsonConfigChanged();

public slots:
    int cmd_exec(const QString &str) { return system(str.toStdString().data()); }

    // 插入值
    void insert(const QString &remark, const QJsonObject &jsonConfig)
    {
        mjsonConfig[remark] = jsonConfig;

        ytool::write_file(address, QJsonDocument(mjsonConfig).toJson().toStdString());
    }

    // 删除
    void remove(const QString &remark)
    {
        if(!mjsonConfig.find(remark)->isNull()) {

            mjsonConfig.remove(remark);
            ytool::write_file(address, QJsonDocument(mjsonConfig).toJson().toStdString());
        }
    }

    // 获取值
    QJsonObject getJsonConfig() { return mjsonConfig; }


private:
    QJsonObject mjsonConfig;
    std::string address = "my_app/ssh/sshconfig.json";

};
